const app = require("./nodelist")()
const Mysql = require("./mysql")
let mysql = new Mysql({
    database: "product"
})
//app.use方法添加组件方法传递两个参数一个路由：默认全部。第二参数回调函数有三个参数req，resp，next。做完操作后必须调用next()传递给下一个参数
//app.post和app.get方法传递两个参数一个路由：默认全部。第二参数回调函数有2个参数req，resp，用req.body获取传递参数body是一个对象 
//req.getcookie("key")返回一个cookie对象，resp.setcookie("key",值)值可以是对象
//设置cookie，必须在req.write()方法前调用否则会报错
//app.all方法表示所有请求(post,get.....)都能接收 传递两个参数一个路由：默认全部。第二参数回调函数有2个参数req，resp
//文件夹映射，将./public/下所有文件共享到login/路径下
app.publicFile("./public/","login/")
app.use((req, resp, next) => { //设置编码
    resp.setHeader('Access-Control-Allow-Origin', '*')
    resp.setHeader('Content-Type', 'text/html; charset=utf-8')
    console.log("ip:",req.socket.remoteAddress);
    console.log(req.url);
    if(req.url=="/favicon.ico"){
        resp.end()
    }else{
     next()   
    }
})
app.use("/login/*", (req, resp, next) => {
    let cookie = req.getcookie("user")
    cookie ? [] : cookie = {}
    cookie.m_id ? [] : cookie.m_id = ''
    cookie.cookie ? [] : cookie.cookie = ''
    let sql = `select * from y_manager where m_id = ${cookie.m_id} and cookie = ${cookie.cookie}`
    mysql.mysql({
        sql
    }).then(data => {
        if (data.length != 0) {
            next()
        } else {
            resp.end("cookie错误")
        }
    }, err => {
        resp.end("cookie错误")
    })
})
app.post("/login", (req, resp) => {
    let user = req.body
    console.log(user);
    let sql = `select * from y_manager where username = '${user.username}' and password = '${user.passwrold}' `
    let cookie = cookienum()
    mysql.mysql({
        sql
    }).then(data => {
        if (data.length != 0) {
            data[0].cookie = cookie
            data[0].nick = undefined
            resp.setcookie("user", data[0])
            resp.write(JSON.stringify(data))
            return mysql.mysql({
                sql: `update y_manager set cookie = '${cookie}' where m_id = '${data[0].m_id}'`
            })
        }else{
            resp.end("密码错误")
        }
    }, err => {
        resp.end("密码错误")
    }).then(data => {
        resp.end()
    })
})
app.get("/login/*", (req, resp) => {
    let sql = 'select * from  product '
    mysql.mysql({
        sql
    }).then(data => {
        resp.end(JSON.stringify(data))
    })
})
app.listen(8090)


function cookienum() {
    return parseInt(Math.random() * 100000000)
}


// let connection = mysql.getConnection({
//     database: "product"
// })
// function getnum() {
//     return parseInt(Math.random() * 1000000000)
// }
// app.post("/login1", (data, req, resp) => {
//     console.log("data", data);
// })
// app.post("/login", (data, req, resp) => {
//     // setcookie(url, key, cookie, expires) 
//     query()
//     async function query() {
//         let result = await mysql.mysql(mysql.getConnection({
//             database: "product"
//         }), {
//             sql: `select * from y_manager where username='${data.username}' and password = '${data.passwrold}'`,
//         })
//         if (result.length != 0) {
//             let cookienum = getnum()
//             console.log("cookie>>>", cookienum);
//             await mysql.mysql(mysql.getConnection({
//                 database: "product"
//             }), {
//                 sql: `update y_manager set cookie=${cookienum} where username='${data.username}'`,
//             })
//             result[0].cookie = cookienum
//             let cookie = {}
//             for (let i in result[0]) {
//                 if (result[0].nick != result[0][i])
//                     cookie[i] = result[0][i]
//                 if (result[0].cookie == result[0][i])
//                     cookie[i] = cookienum
//             }
//             console.log("登录成功", cookie.cookie);
//             app.setcookie("/login", "user", cookie)
//             // console.log(app.getcookie(req.headers.cookie, "user"));
//             resp.write(JSON.stringify(result[0]))
//         }else{
//             resp.write("密码错误")
//         }
//         resp.end()
//     }
// })
// app.get("/prolist", (data, req, resp) => {
//     let cookie
//     console.log("get");
//     try {
//         query()
//         async function query(connection, opction) {
//             cookie = JSON.parse(app.getcookie(req.headers.cookie, "user"))
//             console.log(cookie);
//             if (cookie) {
//                 let result = await mysql.mysql(mysql.getConnection({
//                     database: "product"
//                 }), {
//                     sql: `select * from y_manager where cookie='${cookie.cookie}'`,
//                 })
//                 console.log("getcookie>>>", result);
//                 if (result.length != 0) {
//                     let prolist = await mysql.mysql(mysql.getConnection({
//                         database: "product"
//                     }), {
//                         sql: `select * from product`,
//                     })
//                     resp.write(JSON.stringify(prolist))
//                 } else {
//                     resp.write("cookie不正确")
//                 }
//             } else {
//                 resp.write("未登录")
//             }
//             resp.end()
//         }
//     } catch (error) {
//         cookie = null
//         console.log("cookie>>>" + error);
//         resp.end()
//     }

// })
// app.run(8090)